package model

import (
	"fmt"
)

type User struct {
	Id int
	Name string
}

func (self *User) Query() ([]*User)  {
	query := "select id,name from test.user"
	rows,err := Querys(query)
	if err != nil {
		return nil
	}
	var users []*User
	for rows.Next() {
		var id int
		var name string
		if err = rows.Scan(&id, &name); err != nil {
			panic(err)
		}
		users = append(users, &User{id, name})
	}
	fmt.Println("exec rtn")
	return users
}

func (self *User) Save() (int64,error)  {
	query := "insert into test.user(id,name) values (?,?)"

	state,err := db.Prepare(query)
	defer state.Close()
	if err != nil {
		return -1,err
	}
	res,err := state.Exec(self.Id, self.Name)
	if err != nil {
		return -1,err
	}
	id,err := res.LastInsertId()
	rid,err := res.RowsAffected()
	fmt.Println(string(id) + "===" + string(rid))
	if err != nil {
		return -1,err
	}
	return id,nil
}

func (self *User) GetById() *User  {
	query := "select id,name from test.user where id = ?"
	var id int
	var name string
	err := db.QueryRow(query, self.Id).Scan(&id, &name)
	if err != nil {
		return nil
	}
	return &User{id, name}
}

func (self *User) Update() (int64,error) {
	query := "update test.user set name = ? where id = ?"
	state,err := db.Prepare(query)
	defer state.Close()
	if err != nil {
		return -1, err
	}
	res,err := state.Exec(self.Name, self.Id)
	if err != nil {
		return -1, err
	}
	num,err := res.RowsAffected()
	if err != nil {
		return -1, err
	}
	return num, nil
}

func (self *User) Delete() (int64,error)  {
	query := "delete from test.user where id = ?"
	state,err := db.Prepare(query)
	defer state.Close()
	if err != nil {
		return -1,err
	}
	res,err := state.Exec(self.Id)
	if err != nil {
		return -1,err
	}
	num,err := res.RowsAffected()
	if err != nil {
		return -1,err
	}
	return num, nil
}
